using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Text;

namespace S0017.WebApi.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class ApiController : ControllerBase
  {
    #region 字段
    private static readonly string MessageLogFileName =
      Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web/MessageLog.txt");

    /// <summary>
    /// 编码
    /// </summary>
    private static readonly Encoding MessageLogEncoding = Encoding.GetEncoding("GB18030");

    private readonly ILogger<ApiController> _logger;
    #endregion

    #region 工具集
    #region 保存消息
    /// <summary>
    /// 保存消息
    /// </summary>
    /// <param name="jsonString">Json字符串</param>
    private static void SaveMessage(string jsonString)
    {
      var newContent = jsonString + Environment.NewLine + Environment.NewLine;
      bool isReCreate; //是否覆盖文件，否则追加内容到原来的文件。
      if (System.IO.File.Exists(MessageLogFileName))
      {
        var fileInfo = new FileInfo(MessageLogFileName);
        long fileSize = fileInfo.Length;
        isReCreate = fileSize > 1024 * 1024 * 2; //小于2MB
      }
      else isReCreate = true;

      if (isReCreate)
        System.IO.File.WriteAllText(MessageLogFileName, newContent, MessageLogEncoding);
      else
        System.IO.File.AppendAllText(MessageLogFileName, newContent, MessageLogEncoding);
    }
    #endregion
    #endregion

    #region 构造
    public ApiController(ILogger<ApiController> logger)
    {
      _logger = logger;
    }
    #endregion

    #region 提交消息
    /// <summary>
    /// 提交消息
    /// </summary>
    /// <remarks>在IIS Post网址：http://localhost/S/S0017/WebApi/Api/PostMessage<br/>
    /// 在S4服务器的IIS Post网址：https://s4.sl266.com:82/S/S0017/WebApi/Api/PostMessage<br/>
    /// Visual Studio的http Post网址: http://localhost:5026/Api/PostMessage
    /// </remarks>
    [HttpPost(nameof(PostMessage))]
    public async Task<string> PostMessage()
    {
      var result = "success";
      try
      {
        using var reader = new StreamReader(Request.Body, Encoding.UTF8);
        var jsonString = await reader.ReadToEndAsync();
        
        SaveMessage(jsonString);
      }
      catch (Exception ex)
      {
        result = ex.Message;
        _logger.Log(LogLevel.Error, ex, string.Empty);
      }

      return result;
    }
    #endregion

    /// <summary>
    /// 默认Get动作
    /// </summary>
    /// <remarks>在IIS 网址：http://localhost/S/S0017/WebApi/Api<br/>
    /// 在S4服务器的IIS Post网址：https://s4.sl266.com:82/S/S0017/WebApi/Api<br/>
    /// Visual Studio的http: http://localhost:5026/Api
    /// </remarks>
    [HttpGet]
    public IActionResult Get()
    {
      return Ok(DateTime.Now);
    }
  }
}
